<template>
  <view class="container">
    <!-- 切换金额显示/隐藏的按钮 -->
    <view class="toggle-visibility" @tap="toggleAmountVisibility">
      <text class="icon">{{ showAmount ? '👁️' : '👁️‍🗨️' }}</text>
    </view>

    <!-- 今日收入卡片 -->
    <view class="income-card today">
      <view class="card-header">
        <text class="title">今日已赚</text>
        <text class="status">{{ workStatus }}</text>
      </view>
      <view class="income-content">
        <view class="amount">
          <text class="currency">¥</text>
          <text class="number" :class="{ 'hidden': !showAmount }">
            {{ showAmount ? formatMoney(todayIncome) : '****.**' }}
          </text>
        </view>
        <view class="rate" v-if="isWorking">
          <text class="value" :class="{ 'hidden': !showAmount }">
            {{ showAmount ? `+¥${formatMoney(currentRate)}/时` : '+¥**.**' }}
          </text>
          <text class="label">当前时薪</text>
        </view>
      </view>
    </view>

    <!-- 月度收入卡片 -->
    <view class="income-card month">
      <view class="card-header">
        <text class="title">本月已赚</text>
        <text class="date">{{ currentMonth }}</text>
      </view>
      <view class="income-content">
        <view class="amount">
          <text class="currency">¥</text>
          <text class="number" :class="{ 'hidden': !showAmount }">
            {{ showAmount ? formatMoney(monthIncome) : '****.**' }}
          </text>
        </view>
        <view class="estimate">
          <text class="label">预计收入</text>
          <text class="value" :class="{ 'hidden': !showAmount }">
            {{ showAmount ? `¥${formatMoney(monthEstimate)}` : '¥****.**' }}
          </text>
        </view>
      </view>
      <view class="progress-bar">
        <view class="progress" :style="{ width: monthProgress + '%' }"></view>
        <text class="progress-text">{{ monthProgress }}%</text>
      </view>
    </view>

    <!-- 年度收入卡片 -->
    <view class="income-card year">
      <view class="card-header">
        <text class="title">今年已赚</text>
        <text class="date">{{ currentYear }}年</text>
      </view>
      <view class="income-content">
        <view class="amount">
          <text class="currency">¥</text>
          <text class="number" :class="{ 'hidden': !showAmount }">
            {{ showAmount ? formatMoney(yearIncome) : '****.**' }}
          </text>
        </view>
        <view class="estimate">
          <text class="label">预计收入</text>
          <text class="value" :class="{ 'hidden': !showAmount }">
            {{ showAmount ? `¥${formatMoney(yearEstimate)}` : '¥****.**' }}
          </text>
        </view>
      </view>
      <view class="progress-bar">
        <view class="progress" :style="{ width: yearProgress + '%' }"></view>
        <text class="progress-text">{{ yearProgress }}%</text>
      </view>
    </view>

    <!-- 总收入卡片 -->
    <view class="income-card total">
      <view class="card-header">
        <text class="title">入职已赚</text>
        <text class="date">{{ formatWorkDays(totalWorkDays) }}</text>
      </view>
      <view class="income-content">
        <view class="amount">
          <text class="currency">¥</text>
          <text class="number" :class="{ 'hidden': !showAmount }">
            {{ showAmount ? formatMoney(totalIncome) : '****.**' }}
          </text>
        </view>
        <view class="average">
          <text class="label">月均收入</text>
          <text class="value" :class="{ 'hidden': !showAmount }">
            {{ showAmount ? `¥${formatMoney(monthlyAverage)}` : '¥****.**' }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import workTime from '../../mixins/workTime'

export default {
  name: 'Income',
  mixins: [workTime],

  data() {
    return {
      timer: null,
      todayIncome: 0,
      monthIncome: 0,
      yearIncome: 0,
      totalIncome: 0,
      currentRate: 0,
      totalWorkDays: 0,
      showAmount: true
    }
  },

  computed: {
    ...mapState({
      workSettings: state => state.workSettings
    }),

    currentMonth() {
      return new Date().toLocaleDateString('zh-CN', { month: 'long' })
    },

    currentYear() {
      return new Date().getFullYear()
    },

    monthEstimate() {
      return Number(this.workSettings.salary?.amount) || 0
    },

    yearEstimate() {
      return this.monthEstimate * 12
    },

    monthProgress() {
      const now = new Date()
      const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate()
      return Math.round((now.getDate() / daysInMonth) * 100)
    },

    yearProgress() {
      const now = new Date()
      const startOfYear = new Date(now.getFullYear(), 0, 1)
      const endOfYear = new Date(now.getFullYear() + 1, 0, 1)
      const progress = (now - startOfYear) / (endOfYear - startOfYear)
      return Math.round(progress * 100)
    },

    monthlyAverage() {
      if (!this.totalWorkDays || !this.totalIncome) return 0
      const months = Math.max(this.totalWorkDays / 30, 1)
      return this.totalIncome / months
    },

    workStatus() {
      if (!this.isWorkday) return '非工作日'
      if (!this.isWorking) return '非工作时间'
      return '工作中'
    }
  },

  created() {
    // 从本地存储读取显示状态
    try {
      const visibility = wx.getStorageSync('showAmount')
      this.showAmount = visibility !== false
    } catch (error) {
      console.error('Failed to load amount visibility:', error)
    }
  },

  mounted() {
    this.startTimer()
    this.calculateTotalIncome()
  },

  beforeDestroy() {
    this.clearTimer()
  },

  methods: {
    formatMoney(amount) {
      if (!amount || isNaN(amount)) return '0.00'
      return Number(amount).toFixed(2)
    },

    formatWorkDays(days) {
      const years = Math.floor(days / 365)
      const months = Math.floor((days % 365) / 30)
      const remainingDays = days % 30

      let result = ''
      if (years > 0) result += `${years}年`
      if (months > 0) result += `${months}个月`
      if (remainingDays > 0) result += `${remainingDays}天`
      return result || '刚入职'
    },

    startTimer() {
      this.updateIncome()
      this.timer = setInterval(this.updateIncome, 1000)
    },

    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },

    updateIncome() {
      // 更新今日收入
      const now = new Date()
      const currentTime = now.getHours() * 60 + now.getMinutes() + (now.getSeconds() / 60)
      const morningStart = this.getMinutesFromTime(this.workSettings.morningStart)
      const morningEnd = this.getMinutesFromTime(this.workSettings.morningEnd)
      const afternoonStart = this.getMinutesFromTime(this.workSettings.afternoonStart)
      const afternoonEnd = this.getMinutesFromTime(this.workSettings.afternoonEnd)
      
      if (!this.isWorkday) {
        this.currentRate = 0
        this.todayIncome = 0
        return
      }

      // 计算精确到秒的时薪
      const monthlyRate = this.monthEstimate
      const dailyRate = monthlyRate / 22  // 每月22个工作日
      const hourlyRate = dailyRate / 8    // 每天8小时
      const minuteRate = hourlyRate / 60  // 每分钟收入
      const secondRate = minuteRate / 60  // 每秒收入
      
      this.currentRate = hourlyRate

      // 计算今日已工作时间（分钟）
      let workedMinutes = 0
      const currentTotalMinutes = currentTime

      if (currentTotalMinutes >= morningStart && currentTotalMinutes <= morningEnd) {
        // 上午工作时间
        workedMinutes = currentTotalMinutes - morningStart
      } else if (currentTotalMinutes > morningEnd && currentTotalMinutes < afternoonStart) {
        // 午休时间，只计算上午的工作时间
        workedMinutes = morningEnd - morningStart
      } else if (currentTotalMinutes >= afternoonStart && currentTotalMinutes <= afternoonEnd) {
        // 下午工作时间
        workedMinutes = (morningEnd - morningStart) + (currentTotalMinutes - afternoonStart)
      } else if (currentTotalMinutes > afternoonEnd) {
        // 工作结束
        workedMinutes = (morningEnd - morningStart) + (afternoonEnd - afternoonStart)
      }

      // 确保工作时间不为负数
      workedMinutes = Math.max(0, workedMinutes)

      // 更新今日收入，精确到秒
      const totalSeconds = workedMinutes * 60 + now.getSeconds()
      this.todayIncome = totalSeconds * secondRate
      
      // 更新月度和年度收入
      this.calculateTotalIncome()
    },

    calculateTotalIncome() {
      if (!this.workSettings.joinDate || !this.monthEstimate) {
        this.totalWorkDays = 0
        this.monthIncome = 0
        this.yearIncome = 0
        this.totalIncome = 0
        return
      }

      const joinDate = new Date(this.workSettings.joinDate)
      const now = new Date()
      
      // 计算工作天数
      const diffTime = Math.abs(now - joinDate)
      this.totalWorkDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      // 计算月度收入
      const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate()
      const dayWorked = Math.min(now.getDate(), daysInMonth)
      const dailyRate = this.monthEstimate / daysInMonth
      // 计算本月已完成天数的收入
      const completedDaysIncome = dailyRate * (dayWorked - 1)
      // 加上今天的实时收入
      this.monthIncome = completedDaysIncome + (this.todayIncome || 0)

      // 计算年度收入
      const startOfYear = new Date(now.getFullYear(), 0, 1)
      const daysWorkedThisYear = Math.ceil((now - startOfYear) / (1000 * 60 * 60 * 24))
      // 计算年度日收入
      const yearDailyRate = (this.monthEstimate * 12) / 365
      // 计算已完成天数的收入
      const completedYearDaysIncome = yearDailyRate * (daysWorkedThisYear - 1)
      // 加上今天的实时收入
      this.yearIncome = completedYearDaysIncome + (this.todayIncome || 0)

      // 计算总收入
      const monthsWorked = Math.max(
        ((now.getFullYear() - joinDate.getFullYear()) * 12) + 
        (now.getMonth() - joinDate.getMonth()),
        0
      )
      // 计算已完成月份的收入
      const completedMonthsIncome = this.monthEstimate * monthsWorked
      // 加上本月的实时收入
      this.totalIncome = completedMonthsIncome + (this.monthIncome || 0)
    },

    toggleAmountVisibility() {
      this.showAmount = !this.showAmount
      // 保存显示状态到本地存储
      try {
        wx.setStorageSync('showAmount', this.showAmount)
      } catch (error) {
        console.error('Failed to save amount visibility:', error)
      }
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f8fafc;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.toggle-visibility {
  position: fixed;
  top: 16px;
  right: 16px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
  }

  .icon {
    font-size: 24px;
    line-height: 1;
  }
}

.income-card {
  border-radius: 24px;
  padding: 20px;
  transform: translateY(0);
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(2px);
  }

  &.today {
    background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
    box-shadow: 0 8px 20px rgba(34, 197, 94, 0.15);
  }

  &.month {
    background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%);
    box-shadow: 0 8px 20px rgba(14, 165, 233, 0.15);
  }

  &.year {
    background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
    box-shadow: 0 8px 20px rgba(59, 130, 246, 0.2);
  }

  &.total {
    background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);
    box-shadow: 0 8px 20px rgba(245, 158, 11, 0.2);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .title {
      font-size: 18px;
      color: rgba(255, 255, 255, 0.95);
      font-weight: 600;
      letter-spacing: 0.5px;
    }

    .status, .date {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.8);
      background: rgba(255, 255, 255, 0.15);
      padding: 4px 12px;
      border-radius: 20px;
      backdrop-filter: blur(4px);
    }
  }

  .income-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 16px;

    .amount {
      display: flex;
      align-items: baseline;

      .currency {
        font-size: 20px;
        color: rgba(255, 255, 255, 0.9);
        margin-right: 4px;
      }

      .number {
        font-size: 36px;
        font-weight: 700;
        color: white;
        font-family: 'DIN Alternate', -apple-system, sans-serif;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;

        &.hidden {
          letter-spacing: 2px;
          filter: blur(2px);
          user-select: none;
        }
      }
    }

    .rate, .estimate, .average {
      text-align: right;

      .value {
        font-size: 16px;
        color: rgba(255, 255, 255, 0.95);
        background: rgba(255, 255, 255, 0.15);
        padding: 4px 12px;
        border-radius: 16px;
        display: inline-block;
        transition: all 0.3s ease;

        &.hidden {
          letter-spacing: 1px;
          filter: blur(2px);
          user-select: none;
        }
      }

      .label {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.7);
        margin-top: 4px;
        display: block;
      }
    }
  }

  .progress-bar {
    height: 8px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 4px;
    position: relative;
    margin-top: 16px;
    overflow: hidden;

    .progress {
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 4px;
      transition: width 0.3s ease;
      box-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
    }

    .progress-text {
      position: absolute;
      right: 0;
      top: -20px;
      font-size: 12px;
      color: rgba(255, 255, 255, 0.8);
      background: rgba(255, 255, 255, 0.15);
      padding: 2px 8px;
      border-radius: 10px;
    }
  }

  &::after {
    content: '💖';
    position: absolute;
    right: 16px;
    bottom: 16px;
    font-size: 16px;
    opacity: 0.5;
    transform: rotate(-10deg);
  }

  &.today::after { content: '💰'; }
  &.month::after { content: '🌙'; }
  &.year::after { content: '⭐'; }
  &.total::after { content: '🎉'; }
}

@media (hover: hover) {
  .income-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
  }
}
</style> 